import axios from 'axios'
import config from './config'
import { getToken } from '@/utils/auth'
import store from '@/store'
import { Message, Loading } from 'element-ui'

export default options => {
  return new Promise((resolve, reject) => {
    const service = axios.create({
      baseURL: config.baseUrl,
      headers: config.headers,
      timeout: config.timeout,
      withCredentials: config.withCredentials
    })

    const loadingInstance = Loading.service({
      lock: true,
      text:
        // eslint-disable-next-line no-prototype-builtins
        options.hasOwnProperty('loading') && options.loading
          ? options.loading
          : '数据加载中,请耐心等待...',
      spinner: 'el-icon-loading',
      background: 'rgba(255, 255, 255, 0.5)'
    })
    // request 拦截器
    service.interceptors.request.use(
      config => {
        // 1. 请求开始的时候可以结合 vuex 开启全屏 loading 动画
        // 2. 带上token
        if (store.getters.token) {
          config.headers['Authorization'] = getToken()
        }
        return config
      },
      error => {
        // 请求错误时
        Promise.reject(error)
      }
    )

    // response 拦截器
    service.interceptors.response.use(
      response => {
        return response
      },
      error => {
        return Promise.reject(error)
      }
    )

    // 请求处理
    service(options)
      .then(res => {
        if (res.data && res.data.resultCode && res.data.resultCode !== '200') {
          if (res.data.resultCode === '401') {
            if (!store.state.app.loginCardShow) {
              throw new Error('用户登录信息过期，请重新登录')
            } else {
              return false
            }
          }
          throw new Error(`${res.data.errorDesc}`)
        }
        if (
          // eslint-disable-next-line no-prototype-builtins
          res.headers.hasOwnProperty('authorization') &&
          res.headers.authorization
        ) {
          store.commit('user/SET_TOKEN', res.headers.authorization)
        }
        loadingInstance.close()
        resolve(res)
        return false
      })
      .catch(error => {
        if (error && error.response) {
          switch (error.response.status) {
            case 400:
              error.message = '请求错误'
              break
            case 401:
              error.message = '未授权，请登录'
              break
            case 403:
              error.message = '拒绝访问'
              break
            case 404:
              error.message = `请求未找到`
              break
            case 408:
              error.message = '请求超时'
              break
            case 500:
              error.message = '服务器内部错误'
              break
            case 501:
              error.message = '服务未实现'
              break
            case 502:
              error.message = '网关错误'
              break
            case 503:
              error.message = '服务不可用'
              break
            case 504:
              error.message = '网关超时'
              break
            case 505:
              error.message = 'HTTP版本不受支持'
              break
            default:
          }
          Message.error(
            `请求失败 status code ${error.response.status} ${error.message} 请求地址出错: ${error.response.config.url}`
          )
        } else {
          Message.error(error.message)
        }
        loadingInstance.close()
        reject(error)
      })
  })
}
